package com.livew.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class PermissionInterceptor implements HandlerInterceptor{

	Logger logger = LoggerFactory.getLogger(this.getClass());
	 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.先判断请求url是否有 权限注解  有则代表需要做权限校验 无则直接放行
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        URLPermission permissionService = handlerMethod.getMethodAnnotation(URLPermission.class);
        if (permissionService == null) {
            return true;
        }
 
        //2.走到这里 说明需要对管理员进行操作权限的校验
        //a.查询当前用户
        try {
        	Subject subject = SecurityUtils.getSubject();
            //验证权限
            String url = request.getRequestURI();
            String root = request.getContextPath();
            url = url.replace(root, "").replace("//", "/");
            subject.checkPermission(url);
        } catch (Exception e) {
            logger.error("权限校验失败!");
            response.sendRedirect(request.getContextPath()+"/403");
            return false;
        }
 
        return true;
    }

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
